<template>
 <input type="text" v-model="state.userMessage" v-on:keypress="txtMsgOnKeypress" />
 <div>
  <ul>
    <li v-for="(msg,index) in state.messages" :key="index">{{msg}}</li>
  </ul>
 </div>
</template>

<script>
import {onMounted, reactive} from 'vue'
import * as signalR from '@microsoft/signalr'
let connection;
export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: 'Login',
  setup(){
    const state = reactive({userMessage:"",messages:[]});
    const txtMsgOnKeypress = async function(e){
      if(e.keyCode!=13) return;
      // alert(state.userMessage);
      await connection.invoke("sendPublicMessage",state.userMessage); // sendPublicMessage服务器的方法
      state.userMessage="";
    };
    // 页面加载
    onMounted(async function () {
      connection=new signalR.HubConnectionBuilder()
      .withUrl("https://localhost:7284/MyHub")    //服务器域名+Progress.cs中配置的路径
      .withAutomaticReconnect().build(); // 失败重连
      await connection.start();
      // 监听 ReceivePublicMessage消息
      connection.on("ReceivePublicMessage", msg =>{
        state.messages.push(msg);
      });
    });
    return {state,txtMsgOnKeypress}

  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>
